package work.xiaohong.websocket.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import work.xiaohong.common.constant.StatusCode;
import work.xiaohong.common.eneity.Result;
import work.xiaohong.websocket.client.MyWebSocketClient;
import work.xiaohong.websocket.entity.Friend;
import work.xiaohong.websocket.feign.UserFeign;
import work.xiaohong.websocket.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.v3.oas.annotations.*;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import work.xiaohong.websocket.vo.AddFriendVo;
import work.xiaohong.websocket.vo.FriendQueryVo;
import work.xiaohong.websocket.vo.UserInfoVo;

import javax.websocket.server.PathParam;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xiaohong
 * @version 1.0
 * @date 2021/9/25 0025 15:30
 * @description 好友接口
 */
@Tag(name = "好友接口文档",description = "这是一个好友接口文档")
@RestController
@RequestMapping("/friend")
@CrossOrigin
public class FriendController {

    @Autowired
    private FriendService friendService;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MyWebSocketClient myWebSocketClient;


    /***
     * 查询某用户好友列表
     * @return
     */
    @Operation(summary = "查询某用户好友列表", description = "所需权限：chat-write", security ={@SecurityRequirement(name ="Authorization")})
    @Parameter(in = ParameterIn.QUERY, name = "userId", description = "用户ID", required = true)
    @GetMapping
    public Result findFriendsList(@RequestParam String userId){
        // 查询所有好友
        Friend friend = new Friend();
        friend.setUserId(new BigInteger(userId));
        List<Friend> list = friendService.list(new QueryWrapper<>(friend));

        if (list == null || list.size() <= 0){
            return new Result(true, StatusCode.OK,"查询成功",null) ;
        }

//        Map<String, HashSet<Friend>> map = new HashMap<>();
//
//        // 进行分组
//        for (Friend fd : list) {
//            String group = fd.getFriendGroup();
//            if (!StringUtils.isEmpty(group)){
//                HashSet<Friend> set = map.get(group);
//                if (set != null && set.size() > 0){
//                    set.add(fd);
//                    map.put(group,set);
//                }else {
//                    HashSet<Friend> hashSet = new HashSet<>();
//                    hashSet.add(fd);
//                    map.put(group,hashSet);
//                }
//            }
//        }

        // 查询好友id集合
        List<BigInteger> ids = new ArrayList();
        list.forEach(item -> {
            ids.add(item.getFriendId());
        });

        // 获取好友资料
        List<UserInfoVo> data = userFeign.getByIds(ids).getData();

        // 添加好友分组
        for (int i = 0; i < data.size(); i++) {
            data.get(i).setFriendGroup(list.get(i).getFriendGroup());
        }

        // 查询好友状态
        if (!CollectionUtils.isEmpty(data)){
            for (UserInfoVo datum : data) {
                boolean b = MyWebSocketClient.chatClients.containsKey(datum.getId());
                if (b){
                    datum.setStatus(1);
                }else {
                    datum.setStatus(0);
                }

            }
        }


        return new Result(true, StatusCode.OK,"查询成功",data) ;
    }


    /***
     * 查询某用户某好友的详情
     * @return
     */
    @Operation(summary = "查询某用户某好友的详情", description = "所需权限：chat-write", security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping("/info")
    public Result<UserInfoVo> findFriendInfo(@Validated @RequestBody FriendQueryVo friendQueryVo){
        if (isFriend(friendQueryVo).getData()){
            Result<UserInfoVo> result = userFeign.getById(new BigInteger(friendQueryVo.getFriendId()));
            if (result.getCode() == 20000 && result.getData() != null){
                return new Result<UserInfoVo>(true, StatusCode.OK,"查询成功",result.getData()) ;
            }else {
                return new Result<UserInfoVo>(true, StatusCode.OK,"查询失败","未能找到该好友资料") ;
            }

        }else {
            return new Result<UserInfoVo>(true, StatusCode.OK,"查询失败","你们还不是好友哦~") ;
        }
    }


    /***
     * 判断两用户是否是好友
     * @return
     */
    @Operation(summary = "判断两用户是否是好友",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping("/isFriend")
    public Result<Boolean> isFriend(@Validated @RequestBody FriendQueryVo friendQueryVo){
        Friend friend = new Friend();
        friend.setUserId(new BigInteger(friendQueryVo.getUserId()));
        friend.setFriendId(new BigInteger(friendQueryVo.getFriendId()));

        List<Friend> list = friendService.list(new QueryWrapper<>(friend));
        if (CollectionUtils.isEmpty(list)){
            return new Result<Boolean>(true, StatusCode.OK,"查询成功",false) ;
        }else {
            return new Result<Boolean>(true, StatusCode.OK,"查询成功",true) ;
        }
    }


    /***
     * 新增Friend数据
     * @param addFriendVo
     * @return
     */
    @Transactional
    @Operation(summary = "添加Friend",description = "所需权限：",security ={@SecurityRequirement(name ="Authorization")})
    @PostMapping
    public Result add(@Validated @RequestBody  @Parameter(name = "AddFriendVo对象",required = true) AddFriendVo addFriendVo){
        //双向添加
        Friend application = new Friend();
        application.setUserId(new BigInteger(addFriendVo.getApplicant()));
        application.setFriendId(new BigInteger(addFriendVo.getReceiver()));
        application.setRemark(addFriendVo.getApplicant_remark());
        application.setFriendGroup(addFriendVo.getApplicant_group());


        Friend receiver = new Friend();
        receiver.setUserId(new BigInteger(addFriendVo.getReceiver()));
        receiver.setFriendId(new BigInteger(addFriendVo.getApplicant()));
        receiver.setRemark(addFriendVo.getReceiver_remark());
        receiver.setFriendGroup(addFriendVo.getReceiver_group());

        friendService.save(application);
        friendService.save(receiver);

        return new Result(true,StatusCode.OK,"添加成功");
    }


}
